/***********************************************************************************************************************
*                                                                                                                      *
* SPLASH build system v0.1                                                                                             *
*                                                                                                                      *
* Copyright (c) 2013 Andrew D. Zonenberg                                                                               *
* All rights reserved.                                                                                                 *
*                                                                                                                      *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the     *
* following conditions are met:                                                                                        *
*                                                                                                                      *
*    * Redistributions of source code must retain the above copyright notice, this list of conditions, and the         *
*      following disclaimer.                                                                                           *
*                                                                                                                      *
*    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       *
*      following disclaimer in the documentation and/or other materials provided with the distribution.                *
*                                                                                                                      *
*    * Neither the name of the author nor the names of any contributors may be used to endorse or promote products     *
*      derived from this software without specific prior written permission.                                           *
*                                                                                                                      *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES        *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR       *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE       *
* POSSIBILITY OF SUCH DAMAGE.                                                                                          *
*                                                                                                                      *
***********************************************************************************************************************/

#include "splashcore.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction

MultiFileROMImage::MultiFileROMImage(
	BuildGraph* graph,
	std::string arch,
	size_t maxwordsize,
	string name)
	: BuildGraphNode(graph)
	, m_arch(arch)
	, m_maxwordsize(maxwordsize)
	, m_name(name)
{

}

MultiFileROMImage::~MultiFileROMImage()
{
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Dependency scanning

string MultiFileROMImage::GetHash()
{
	DebugPrintfHeading(4, "MultiFileROMImage::GetHash() [node = \"%s\"]\n", m_name.c_str());
	string hashin = "";
	
	//Update our dependencies
	UpdateDependencies();
	
	//Add data at this node
	char tmp[128];
	snprintf(tmp, sizeof(tmp), "%zu", m_maxwordsize);
	hashin += sha256(tmp);
	for(auto x : m_entries)
	{
		snprintf(tmp, sizeof(tmp), "%zu", x.m_len);
		hashin += sha256(tmp);
	}
	
	//Add data for our dependencies
	for(size_t i=0; i<m_dependencies.size(); i++)
		hashin += m_dependencies[i]->GetHashCached(); 
	return sha256(hashin);
}

void MultiFileROMImage::UpdateDependencies()
{
	DebugPrintfHeading(4, "MultiFileROMImage::UpdateDependencies() [node = \"%s\"]\n", m_name.c_str());
	m_dependencies.clear();

	for(auto x : m_entries)
		m_dependencies.push_back(x.m_file);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Compilation

string MultiFileROMImage::GetOutputPath()
{
	return m_graph->GetOutDir() + "/" + m_arch + "/" + m_name + ".bin";
}

string MultiFileROMImage::GetDescription()
{
	char desc[1024];
	snprintf(desc, sizeof(desc), "Multi-file ROM image %s [%s]", m_name.c_str(), m_arch.c_str());
	return string(desc);
}

string MultiFileROMImage::GetBinaryPath()
{
	return m_graph->GetMetaDir() + "/" + GetHashCached()  + "/" + m_name + ".bin";
}

void MultiFileROMImage::Update(Cluster* cluster)
{
	//Rebuild all of our dependencies if necessary
	vector<ClusterJob*> deps;
	for(size_t i=0; i<m_dependencies.size(); i++)
	{		
		BuildGraphNode* node = m_dependencies[i];
		node->UpdateCached(cluster);
		if(node->GetBuildJob() != NULL)
			deps.push_back(node->GetBuildJob());
	}
	
	//Get output directory etc
	string rom_filename = GetBinaryPath();
	string path = GetDirOfFile(rom_filename);
	string base = GetBasenameOfFile(rom_filename);
	string basewe = GetBasenameOfFileWithoutExt(rom_filename);
	
	//Print the heading
	DebugPrintfHeading(3, "Generating ROM image %s\n", base.c_str());

	//Create the batch script
	string batch_fname = path + "/rom_batch_command_" + basewe + ".sh";
	FILE* fp = fopen(batch_fname.c_str(), "w");
	if(!fp)
		FatalError("Failed to create batch script %s\n", batch_fname.c_str());
	fprintf(fp, "#!/bin/bash\n");
	
	//Process input files, one at a time
	fprintf(fp, "touch out.bin\n");
	for(auto x : m_entries)
	{
		//Pad input file up to at LEAST the desired size
		fprintf(fp, "dd if=/dev/zero of=nulls.bin bs=4 count=%zu > /dev/null 2> /dev/null\n", x.m_len);
		fprintf(fp, "cat %s nulls.bin > padded.bin\n", x.m_file->GetOutputPath().c_str());
		
		//Truncate to EXACTLY the desired size
		fprintf(fp, "dd if=padded.bin of=truncated.bin bs=4 count=%zu > /dev/null 2> /dev/null\n", x.m_len);
		
		//Append to the existing file
		fprintf(fp, "cat truncated.bin >> out.bin\n");
	}
	
	//Pad and truncate output file
	fprintf(fp, "dd if=/dev/zero of=nulls.bin bs=4 count=%zu > /dev/null 2> /dev/null\n", m_maxwordsize);
	fprintf(fp, "cat out.bin nulls.bin > padded.bin\n");
	fprintf(fp, "dd if=padded.bin of=%s bs=4 count=%zu > /dev/null 2> /dev/null\n",
		rom_filename.c_str(), m_maxwordsize);
	fprintf(fp, "rm -f out.bin padded.bin nulls.bin truncated.bin\n");
		
	//Done
	fprintf(fp, "touch build_successful\n");
	fclose(fp);
	if(0 != chmod(batch_fname.c_str(), 0755))
		FatalError("Failed to set execute permissions on batch script %s\n", batch_fname.c_str());
		
	//Submit the batch script
	m_job = cluster->SubmitBatchJob(batch_fname, cluster->m_cppBuildPartition, path, deps);
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Factory method

MultiFileROMImage* MultiFileROMImage::CreateMultiFileROMImage(
	BuildGraph* graph,
	string arch,
	size_t maxwordsize,
	string name,	
	bool target)
{
	//Add the executable node
	MultiFileROMImage* node = new MultiFileROMImage(graph, arch, maxwordsize, name);
	graph->AddNodeWithPath(node, node->GetOutputPath(), arch);
	
	//Add it as a top-level target if requested
	if(target)
		graph->AddTarget(node, node->GetTargetName());
	
	//Done
	return node;
}

string MultiFileROMImage::GetTargetName() const
{
	return m_name + "-rom-" + m_arch;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Accessors

void MultiFileROMImage::AddFile(RomImageEntry entry)
{
	m_entries.push_back(entry);
}
